import { registerGLTFLoader } from '../loaders/gltf-loader'
import registerOrbit from "./orbit"

export function renderModel(canvas, THREE, rotateAngle,url) {
  registerGLTFLoader(THREE)

  var container, stats, clock, gui, mixer, actions, activeAction, previousAction;
  var camera, scene, renderer, model, face, controls;
  var api = { state: 'Walking' };
   // 正确地清理已有场景
   if (scene) {
    // 清理场景中的所有对象
    while(scene.children.length > 0) { 
      scene.remove(scene.children[0]); 
    }
  }
  
  init();
  animate();
  function init() {
    scene = new THREE.Scene();
    // 创建组并添加到场景
    const cameraGroup = new THREE.Group();
    scene.add(cameraGroup);
    camera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 0.25, 100);
   
    // 修改相机初始位置，使其正对中心点
    // camera.position.set(1, 1, 1);  // 从正面观察模型
    // camera.lookAt(0, 0, 0);        // 看向中心点
    // 将相机添加到组中
    cameraGroup.add(camera);
    cameraGroup.rotation.set(0, Math.PI / rotateAngle, 0); 

    scene.background = null; // 透明背景
    scene.fog = new THREE.Fog(0xe0e0e0, 20, 100);
    // lights
    var light = new THREE.AmbientLight(0xeeeeee);
    light.position.set(0, 20, 0);
    scene.add(light);
    // model
    var loader = new THREE.GLTFLoader();
    loader.load(url, function (gltf) {
      // model = gltf.scene;
      // model.scale.set(1.5, 1.5, 1.5); // 将模型放大1.5倍
      // // 使用包围盒确保模型居中
      // const box = new THREE.Box3().setFromObject(model);
      // const center = box.getCenter(new THREE.Vector3());
      
      // // 将模型中心移动到原点
      // model.position.x = -center.x;
      // model.position.y = -center.y;
      // model.position.z = -center.z;
  
      // scene.add(model);
      const model = gltf.scene;
        scene.add(model);

        // 1. 计算模型的包围盒 (Bounding Box)
        const box = new THREE.Box3().setFromObject(model);
        const size = new THREE.Vector3();
        box.getSize(size); // size向量现在包含了模型在x, y, z方向上的尺寸

        // 2. 确定最大尺寸（或使用对角线长度）
        const maxDim = Math.max(size.x, size.y, size.z); // 使用最大边长
        // const diagonal = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z); // 或者使用对角线

        // 3. 定义目标尺寸（根据你的场景需求设定）
        const targetSize = 4; // 例如，希望模型最大维度缩放为5个单位

        // 4. 计算缩放比例并应用（均匀缩放）
        const scale = targetSize / maxDim;
        model.scale.set(scale, scale, scale);

        // 5. (可选但推荐) 将模型中心移动到原点，便于旋转和观察
        const center = new THREE.Vector3();
        box.getCenter(center);
        model.position.sub(center); // 模型原点移回(0,0,0)

        // 6. 调整相机位置和控制器目标点
        // 重新计算缩放后的包围盒和中心（因为模型缩放和移动了）
        const newBox = new THREE.Box3().setFromObject(model);
        const newSize = new THREE.Vector3();
        newBox.getSize(newSize);
        const newCenter = new THREE.Vector3();
        newBox.getCenter(newCenter);

        const newMaxDim = Math.max(newSize.x, newSize.y, newSize.z);
        const fov = camera.fov * (Math.PI / 180); // 转换为弧度
        // 计算相机距离，确保模型完整在视野内，额外乘以一个系数（如1.5）留有余地
        let cameraDistance = (newMaxDim / (2 * Math.tan(fov / 2))) * 1.5;

        // 设置相机位置，假设相机初始朝向负Z轴
        camera.position.set(3, 3, cameraDistance);
        camera.lookAt(newCenter); // 相机看向模型中心
        camera.updateProjectionMatrix();

        // 如果使用了OrbitControls，更新控制器的目标
        if (controls) {
            controls.target.copy(newCenter);
            controls.update();
        }

        console.log('模型加载并缩放完成。');
    }, undefined, function (e) {
      console.error(e);
    });
    // renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer = new THREE.WebGLRenderer({ 
      alpha: true,  // 启用透明背景
      premultipliedAlpha: false  // 禁用预乘 alpha
    });
    renderer.setPixelRatio(wx.getSystemInfoSync().pixelRatio);
    renderer.setSize(canvas.width, canvas.height);
    // renderer.gammaOutput = true;
    // renderer.gammaFactor = 2.2;

    const { OrbitControls } = registerOrbit(THREE)
    controls = new OrbitControls( camera, renderer.domElement );

    
    controls.update();
  }

  function fadeToAction(name, duration) {
    previousAction = activeAction;
    activeAction = actions[name];
    if (previousAction !== activeAction) {
      previousAction.fadeOut(duration);
    }
    activeAction
      .reset()
      .setEffectiveTimeScale(1)
      .setEffectiveWeight(1)
      .fadeIn(duration)
      .play();
  }
  function animate() {
    canvas.requestAnimationFrame(animate);
    controls.update()
    renderer.render(scene, camera);
  }
}